<template>
  <a-card class="fromBox" title="资金使用申请">
    <template #extra>
      <a-tooltip placement="top">
        <template #title>
          <span>返回上级</span>
        </template>
        <a-button size="small" @click="getOut"> <RollbackOutlined /></a-button>
      </a-tooltip>
    </template>
    <div class="proMange-content">
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" labelWrap="true">
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">项目信息:</h4>
          <a-form-item label="项目编号" name="blprojectnum">
            <a-select v-model:value="formState.blprojectnum" placeholder="请选择项目编号" :showSearch="false" allowClear @change="handleSelectChange">
              <a-select-option :value="item.blext2" v-for="(item, index) in NameNumber"
                >{{ item.blext2 }}—{{ item.blapplyprojectname }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="项目名称" name="blapplyprojectname">
            <a-input v-model:value="formState.blapplyprojectname" placeholder="请填写" disabled />
          </a-form-item>
          <a-form-item label="申请日期" name="blapplytime">
            <a-date-picker v-model:value="formState.blapplytime" :valueFormat="'YYYY-MM-DD'" />
          </a-form-item>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">申请人信息:</h4>
          <a-form-item label="联系人姓名" name="bllinkmanname">
            <a-input v-model:value="formState.bllinkmanname" placeholder="请填写" />
          </a-form-item>
          <a-form-item label="执行单位" name="bldeptnum">
            <a-select v-model:value="formState.bldeptnum" placeholder="请选择执行单位" :showSearch="false" allowClear>
              <a-select-option :value="`${item.bldeptid}`" v-for="(item, index) in DeportList">{{ item.blname }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="电话" name="blphone">
            <a-input v-model:value="formState.blphone" placeholder="请填写" />
          </a-form-item>
          <a-form-item label="邮箱" name="blemail">
            <a-input v-model:value="formState.blemail" placeholder="请填写" />
          </a-form-item>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">申请事由:</h4>
          <a-form-item label="申请事由" name="blusecontent" :wrapper-col="{ span: 15, offset: 0 }">
            <a-textarea v-model:value="formState.blusecontent" :rows="4" placeholder="请填写" />
          </a-form-item>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">项目进展:</h4>
          <a-form-item label="项目进展" name="blauditopinionm" :wrapper-col="{ span: 15, offset: 0 }">
            <a-textarea v-model:value="formState.blauditopinionm" :rows="4" placeholder="请填写" />
          </a-form-item>
        </div>
        <div style="text-align: center">
          <h4 style="font-size: 25px; color: #478fca !important; font-weight: bolder; padding-top: 20px">资金使用详细说明</h4>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">人员支出:</h4>
          <template v-for="(item, index) in TableListOne">
            <a-form-item :label="item.bldataname">
              <a-input-number v-model:value="item.bltotle" placeholder="例:10.00" style="width: 100px" :step="0.01" :min="0" />
              <a-textarea v-model:value="item.bldetail" :rows="3" placeholder="备注" />
            </a-form-item>
          </template>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">公用支出:</h4>
          <template v-for="(item, index) in TableListTwo">
            <a-form-item :label="item.bldataname">
              <a-input-number v-model:value="item.bltotle" placeholder="例:10.00" style="width: 100px" :step="0.01" :min="0" />
              <a-textarea v-model:value="item.bldetail" :rows="3" placeholder="备注" />
            </a-form-item>
          </template>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">基建支出:</h4>
          <template v-for="(item, index) in TableListThree">
            <a-form-item :label="item.bldataname">
              <a-input-number v-model:value="item.bltotle" placeholder="例:10.00" style="width: 100px" :step="0.01" :min="0" />
              <a-textarea v-model:value="item.bldetail" :rows="3" placeholder="备注" />
            </a-form-item>
          </template>
        </div>
        <div>
          <h4 style="font-size: 17px; color: #478fca !important; font-weight: bolder">其他资本性支出:</h4>
          <template v-for="(item, index) in TableListFour">
            <a-form-item :label="item.bldataname">
              <a-input-number v-model:value="item.bltotle" placeholder="例:10.00" style="width: 100px" :step="0.01" :min="0" />
              <a-textarea v-model:value="item.bldetail" :rows="3" placeholder="备注" />
            </a-form-item>
          </template>
        </div>
      </a-form>
      <div style="text-align: center; padding: 40px 0">
        <a-space>
          <a-button type="primary" @click="onSubmit"><CheckOutlined /> 提交 </a-button>
          <a-button @click="getOut"> <RollbackOutlined />返回 </a-button>
        </a-space>
      </div>
    </div>
  </a-card>
</template>

<script setup>
  import { reactive, ref, defineEmits, onMounted, toRaw, watch, defineProps } from 'vue';
  import { message } from 'ant-design-vue';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { ProManageApi } from '../../../api/ProManage/ProManage-api';
  const props = defineProps({
    DateId: String,
  });
  //项目名称编号
  const NameNumber = ref();
  const getIniteNameNum = async () => {
    try {
      let res = await ProManageApi.ProjectNameNum();
      NameNumber.value = res.data;
    } catch (error) {
      smartSentry.captureError(error);
    }
  };
  //执行单位
  const DeportList = ref();
  const DeportInite = async () => {
    try {
      let res = await ProManageApi.DeportInit();
      DeportList.value = res.data;
    } catch (error) {
      smartSentry.captureError(error);
    }
  };
  //表单数据
  const TableListOne = ref([]);
  const TableListTwo = ref([]);
  const TableListThree = ref([]);
  const TableListFour = ref([]);
  let formState = ref({});
  let blrecordVo = reactive([]);
  async function getInitFrom() {
    try {
      let res = await ProManageApi.TableInite();
      TableListOne.value = res.data[0].children;
      TableListTwo.value = res.data[1].children;
      TableListThree.value = res.data[2].children;
      TableListFour.value = res.data[3].children;
      blrecordVo = [...TableListOne.value, ...TableListTwo.value, ...TableListThree.value, ...TableListFour.value];
      TableInite();
    } catch (error) {
      smartSentry.captureError(error);
    }
  }
  const fromHoistry = ref();
  async function TableInite() {
    try {
      let blapplyid = props.DateId;
      let res = await ProManageApi.ProMangeHoistry(blapplyid);
      console.log(res, 'res历史');
      formState.value = res.blapply; //拿到表单
      fromHoistry.value = res.blapply.blrecordVo;
      // 创建一个 Map 查找出两个编号一样的
      const map1 = new Map(fromHoistry.value.map((item) => [item.bldatanum, item]));
      // 利用数组对象响应式，更新 合并后blrecordVo数组，就现对于更新了页面中循环的TableListOne two three four 数组
      blrecordVo.forEach((item) => {
        //将另个编号一样并且有值的数组，插入到blrecordVo数组中
        const match = map1.get(item.bldatanum);
        if (match) {
          item.bldetail = match.bldetail;
          item.bltotle = match.bltotle;
          item.blext2 = match.blext2;
          item.blrecordid = match.blrecordid;
        }
      });
    } catch (error) {
      smartSentry.captureError(error);
    }
  }

  function handleSelectChange(value) {
    // 根据选择的项目编号查找对应的项目名称
    const selectedItem = NameNumber.value.find((item) => item.blext2 == value);
    if (selectedItem) {
      formState.value.blapplyprojectname = selectedItem.blapplyprojectname; //拿到年度预算的名称和id
      formState.value.blbudgetid = selectedItem.blbudgetid;
    } else {
      formState.value.blapplyprojectname = ''; // 如果没有找到匹配项
    }
  }
  //表单验证规则
  const formRef = ref();
  const labelCol = {
    span: 5,
  };
  const wrapperCol = {
    span: 15,
  };

  const rules = {
    blprojectnum: [
      {
        required: true,
        message: '请选择项目编号',
        trigger: 'change',
      },
    ],
    blapplyprojectname: [
      {
        required: true,
        message: '请填写项目名称',
        trigger: 'change',
      },
    ],
    blapplytime: [
      {
        required: true,
        message: '请选择申请日期',
        trigger: 'change',
      },
    ],
    bllinkmanname: [
      {
        required: true,
        message: '请填写联系人姓名',
        trigger: 'change',
      },
    ],
    bldeptnum: [
      {
        required: true,
        message: '请选择执行单位',
        trigger: 'change',
      },
    ],
    blphone: [
      {
        required: true,
        message: '请填写电话',
        trigger: 'blur',
      },
      {
        validator: (rule, value) => {
          // 自定义严重验证逻辑
          if (!/^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/.test(value)) {
            return Promise.reject('电话格式不正确');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
    blemail: [
      {
        required: true,
        message: '请填写邮箱',
        trigger: 'blur',
      },
      {
        validator: (rule, value) => {
          // 自定义验证逻辑
          if (!/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/.test(value)) {
            return Promise.reject('邮箱格式不正确');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
    blusecontent: [
      {
        required: true,
        message: '请填写申请事由',
        trigger: 'blur',
      },
    ],
    blauditopinionm: [
      {
        required: true,
        message: '请填写项目进展',
        trigger: 'blur',
      },
    ],
  };
  const onSubmit = () => {
    const filteredArray = blrecordVo.map(({ blbudgetdataid, bldataname, children, ...rest }) => rest);
    // 提示用户如果所有对象都没有“bldetail”或“bltotle”
    const hasDetailOrTotal = filteredArray.some((item) => item.bltotle);
    // 删除所有没有“bldetail”和“bltotle”的对象
    const finalArray = filteredArray.filter((item) => item.bltotle);
    formState.value.blrecordVo = finalArray;
    console.log(finalArray, 'finalArray');
    formRef.value
      .validate()
      .then(() => {
        if (!hasDetailOrTotal) {
          message.warning('金额项至少添一项');
        } else {
          let queryForm = { ...toRaw(formState.value) };
          delete queryForm.blapplyprojectname;
          queryForm.blaudit = 1; //将状态编辑后，重新进入审核流
          queryForm.blcheck = 0; //一旦回到修改就证明被驳回过
          getAddFound(queryForm);
        }
      })
      .catch((error) => {
        message.warning('请检查表单是否有未填写或者格式错误');
      });
  };
  //添加方法
  function getAddFound(queryForm) {
    ProManageApi.ProMangeUpdate(queryForm)
      .then((res) => {
        message.success('修改成功');
        resetForm();
        getOut();
      })
      .catch((e) => {
        smartSentry.captureError(e);
      });
  }
  const resetForm = () => {
    formRef.value.resetFields();
  };
  const emit = defineEmits();
  //返回表格
  const getOut = () => {
    let obj = {
      type: 0,
    };
    emit('getBlack', obj);
  };

  onMounted(() => {
    getInitFrom();
    getIniteNameNum();
    DeportInite();
  });
</script>

<style lang="scss" scoped>
  .proMange-content {
    width: 75%;
    min-height: 510px;
    padding-top: 40px;
    margin: 20px auto;
  }

  .steps-action {
    margin-top: 24px;
    float: right;
  }

  [data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
  }

  .jianjie span {
    display: block;
    font-size: 16px;
    padding-bottom: 20px;
    padding-left: 20px;
  }
</style>
